const crypto = require('crypto');

const keyPair = crypto.generateKeyPairSync('rsa', {
  modulusLength: 512, // 密钥长度[512, 1024, 2048, 4096]
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: '123456', // 私钥密码，可以不填
  },
});

const publicKey = keyPair.publicKey;
const privateKey = keyPair.privateKey;

const plain = 'Hello RSA!';
const encryptResult = crypto.publicEncrypt(
  {
    key: publicKey,
    padding: crypto.constants.RSA_PKCS1_PADDING,
  },
  Buffer.from(plain)
);

const decryptResult = crypto.privateDecrypt(
  {
    key: privateKey,
    padding: crypto.constants.RSA_PKCS1_PADDING,
    passphrase: '123456',
  },
  encryptResult
);

const sign = crypto.createSign('SHA256');
sign.write(plain);
sign.end();
const signResult = sign.sign(
  {
    key: privateKey,
    padding: crypto.constants.RSA_PKCS1_PADDING,
    passphrase: '123456',
  },
  'base64'
);
const verify = crypto.createVerify('SHA256');
verify.write(plain);
verify.end();
const verifyResult = verify.verify(publicKey, signResult, 'base64');

console.log('公钥', publicKey);
console.log('私钥', privateKey);
console.log('原文', plain);
console.log('公钥加密', encryptResult.toString('base64'));
console.log('私钥解密', decryptResult.toString());
console.log('私钥签名', signResult);
console.log('公钥验签', verifyResult);
